package com.journey.org.ui.login

import android.app.Application
import android.text.TextUtils
import androidx.databinding.ObservableField
import com.journey.org.app.HttpManager
import com.journey.org.app.requestBase
import com.journey.org.app.requestHttpManager
import com.journey.org.entity.LoginEntity
import com.journey.org.ui.MainActivity
import com.mvvmhabit.org.base.BaseViewModel
import com.mvvmhabit.org.binding.command.BindingAction
import com.mvvmhabit.org.binding.command.BindingCommand
import com.mvvmhabit.org.custom.LoadingLayout
import com.mvvmhabit.org.utils.SPUtils
import com.mvvmhabit.org.utils.ToastUtils

class LoginViewModel(application: Application) : BaseViewModel(application) {

    val onInputLoginNameField =
        ObservableField(SPUtils.getInstance().getString(SPUtils.Config.USER_NAME, ""))

    val onInputPasswordField =
        ObservableField(SPUtils.getInstance().getString(SPUtils.Config.USER_PSW, ""))

    // 点击登录
    val onCLickLoginCommand = BindingCommand<Any>(object : BindingAction {
        override fun call() {
            login()
        }
    })

    private fun login() {
        if (TextUtils.isEmpty(onInputLoginNameField.get())) {
            ToastUtils.showShort("请输入账户！")
            return
        }
        if (TextUtils.isEmpty(onInputPasswordField.get())) {
            ToastUtils.showShort("请输入密码！")
            return
        }
        val params = HashMap<String, Any>()
        params["username"] = onInputLoginNameField.get()!!
        params["password"] = onInputPasswordField.get()!!
        params["grant_type"] = "password"
        params["client_secret"] = "123456"
        params["client_id"] = "journey-admin"
        showLoadDialog("正在登录中...")
        requestBase<LoginEntity> {
            requestHttpManager {
                onLoader {
                    login(params)
                }
                onSuccess {
                    SPUtils.getInstance()
                        .put(SPUtils.Config.USER_TOKEN, it.token_type + " " + it.access_token)
                    SPUtils.getInstance().put(SPUtils.Config.REFRESH_TOKEN, it.refresh_token)
                    SPUtils.getInstance().put(SPUtils.Config.TOKEN_EXPIRES_IN, it.expires_in)
                    SPUtils.getInstance().put(SPUtils.Config.USER_NAME, it.username)
                    SPUtils.getInstance().put(SPUtils.Config.USER_ID, it.userId)
                    SPUtils.getInstance().put(SPUtils.Config.USER_PSW, onInputPasswordField.get()!!)
                    ToastUtils.showShort("登录成功！")
                    finish()
                }
                onComplete {
                    dismissLoadDialog()
                }
            }
        }
    }
}